package cn.maidouya.org.service.impl;

import cn.maidouya.basic.service.BaseService;
import cn.maidouya.basic.service.impl.BaseServiceImpl;
import cn.maidouya.basic.util.PageList;
import cn.maidouya.org.domain.Department;
import cn.maidouya.org.mapper.DepartmentMapper;
import cn.maidouya.org.query.DepartmentQuery;
import cn.maidouya.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService{
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        if (department.getParent()==null){
            department.setDirPath("/"+ department.getId());
        }else {
            Long parentId = department.getParent().getId();
            Department departPatenId = departmentMapper.loadById(parentId);
            String dirPath = departPatenId.getDirPath();
            department.setDirPath(dirPath + "/" + department.getId());
        }
        System.out.println("添加： " + department);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent().getId() == null){
            department.setDirPath("/" +department.getId());
        }
        if (department.getParent().getId() != null){
            // 上级部门和部门数据关联关系  简介模式
            /*String dirPath = departmentMapper.findOne(department.getParent().getId()).getDirPath();
            department.setDirPath(dirPath + "/" +department.getId());*/
            // 上级部门和部门数据关联关系   流程模式
            Long perentId = department.getParent().getId();
            Department parentDept = departmentMapper.loadById(perentId);
            String parentDirPath = parentDept.getDirPath();
            Long deptId = department.getId();
            String newParent = parentDirPath + "/" +deptId;
            department.setDirPath(newParent);

        }
        departmentMapper.update(department);
    }


    @Override
    @Transactional// 开启批量删除事件
    public void batchDel(Long[] ids) {
        departmentMapper.batchDel(ids);
    }

    /**
     *    查询上级部门
     * @return
     */
    @Override
    public List<Department> getDepttree() {
        List<Department> list = departmentMapper.getDepttree();
        return list;
    }
}
